import json
import requests
from typing import Dict, Any

from Decryption.decryption import get_token, get_boat_flow_list

# api地址
boat_url = 'http://localhost:5000/api/boat'
portflow_url = 'http://localhost:5000/api/portflow'
boatName_url = 'http://10.1.161.53:5000/api/boatName'
warning_url = 'http://10.1.161.53:5000/api/warning'

# 合法api名
API_STRATEGIES = {
    "vessel_trajectory", "checkpoint_passage", "violation_detection", "checkpoint_traffic", "not matched", "basic_information"
}

def call_api(request_params: Dict[str, Any]) -> Dict[str, Any]:

    global cleaned_rows, payload
    cleaned_rows = []
    api_type = request_params.get('api')
    parameters = request_params.get('parameters', {})

    if not api_type or api_type not in API_STRATEGIES:
        raise ValueError(f"未定义的API类型: {api_type}")

    try:
        # 获取船只的航线轨迹数据
        if api_type == 'vessel_trajectory':

            payload = {
                "boatName": parameters.get("boatName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }
            # 获取密钥token
            token = get_token()
            print(token)
            # 调用船舶流量接口
            data = get_boat_flow_list(token, payload)
            print("数据库查询成功")
            print(data)

            # 数据处理
            for row in data.get("rows", []):
                cleaned_row = {
                    k: v for k, v in row.items()
                    if k not in ["imagePaths", "imageUrls", 'bayonetId', 'code', 'endPoint', 'locationMapx', 'locationMapy']
                }
                cleaned_rows.append(cleaned_row)
            print("获取到的数据字段清理成功")
            print(cleaned_rows)

        # 监控船只经过卡口（检查点）的情况
        elif api_type in ["checkpoint_passage"]:

            payload = {
                "boatName": parameters.get("boatName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(boat_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 数据处理
            for row in response_result.get("result", []):
                cleaned_row = {
                    k: v for k, v in row.items()
                    if k not in ["CODE", "HEIGHT", "LENGTH", "WIDTH", "LOAD", "SPEED"]
                }
                cleaned_rows.append(cleaned_row)
            print("获取到的数据字段清理成功")
            print(cleaned_rows)

        # 预警相关（船舶在哪个卡口哪个时间有哪个预警）
        elif api_type in ["violation_detection"]:

            payload = {
                "boatName": parameters.get("boatName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(warning_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 数据处理
            for row in response_result.get("result", []):
                cleaned_row = {
                    k: v for k, v in row.items()
                    if k not in ["warncode", "photoname", "photoposition", "msgsendstatus", "bayonetid"]
                }
                cleaned_rows.append(cleaned_row)
            print("获取到的数据字段清理成功")
            print(cleaned_rows)

        # 查询特定卡口通过的船舶信息
        elif api_type in ["checkpoint_traffic"]:

            payload = {
                "bayonet_name": parameters.get("checkpointName"),
                "startTime": parameters.get("startTime"),
                "endTime": parameters.get("endTime")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(portflow_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 数据处理
            cleaned_rows = response_result.get("result")
            print("该问题查询结果不需要清理")
            print(cleaned_rows)

        # 获取船只的基本信息
        elif api_type == 'basic_information':

            payload = {
                "boatName": parameters.get("boatName")
            }

            headers = {'Content-Type': 'application/json'}
            response = requests.post(boatName_url, data=json.dumps(payload), headers=headers)
            response_result = response.json()
            print("数据库查询成功")
            print(response_result)

            # 数据处理
            cleaned_rows = response_result.get("result")
            print("该问题查询结果不需要清理")
            print(cleaned_rows)

        # not matched 或者其它情况
        else:
            payload = parameters

        result = {
            "api": api_type,
            "payload": payload,
            "data": cleaned_rows
        }
        return result

    except requests.exceptions.RequestException as e:
        print(f"API调用失败（{api_type}）: {str(e)}")
        raise


# 使用示例（使用用户提供的参数）
# if __name__ == "__main__":
#     request_params = {
#         "api": "violation_detection",
#         "parameters": {
#             "boatName": "兴安太518",
#             "startTime": "2025-04-01 00:00:00",
#             "endTime": "2025-04-18 23:59:59",
#             "checkpointName": None,
#             "waterwayName": None
#         }
#     }
#
#     try:
#         result = call_api(request_params)
#         data = result.get('data')
#         print("API返回结果:", result)
#     except Exception as e:
#         print("处理失败:", e)